/**
 * Copyright(C) 2012 Luvina
 * EmailValidator.java, 26-05-2012 NguyenVietDung
 */
package net.luvina.manageuser.validator;

import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import net.luvina.manageuser.util.Message;

/**
 * EmailValidator: Custome validate của JSF Thực hiện validate dữ liệu nhập vào
 * cho hạng mục email
 *
 * @author NguyenVietDung
 */
public class EmailValidator implements Validator {
	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * javax.faces.validator.Validator#validate(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public void validate(FacesContext context, UIComponent component, Object str) throws ValidatorException {
		FacesMessage message = new FacesMessage();
		String labelField = (String) component.getAttributes().get("label");
		String emailStr = String.valueOf(str);
		String emailPattern = "[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+.[a-z]{2,7}$";
		boolean isMatch = Pattern.matches(emailPattern, emailStr);
		String emailFormat = "xxxx@xxxx.xxxx";
		if (!isMatch) {
			StringBuilder msgStr = new StringBuilder();
			msgStr.append(" 「").append(labelField).append("」 を ").append(emailFormat + " ").append(Message.getString("ER005_email"));
			message.setDetail(msgStr.toString());
			message.setSummary(msgStr.toString());
			throw new ValidatorException(message);
		}
		if (emailStr.length() >= 100) {
			StringBuilder msgStr = new StringBuilder();
			msgStr.append("100 桁以内の ");
			msgStr.append(" 「").append(labelField).append("」 ").append(Message.getString("ER006_email"));
			message.setDetail(msgStr.toString());
			message.setSummary(msgStr.toString());
			throw new ValidatorException(message);
		}

	}
}
